package com.ctrip.corp.obt.shard.sql.parser.forbidden;

import static com.ctrip.corp.obt.shard.constants.MaskConstants.DEFAULT_DESENSITIZATION_NAMES;
import static com.ctrip.corp.obt.shard.constants.MaskConstants.MASK_PATTERN;

import java.util.Optional;

import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.shard.configuration.DataShardProperties;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 对字段名非常用脱敏类型名，但名称带*的掩码数据，记录日志
 * 
 * @author xukang zhang
 * @date 2023/8/30 18:58
 */
@AllArgsConstructor
@Slf4j
@Deprecated
public class MaskLoggerMatcher implements UpdateForbiddenMatcher {

    private final DataShardProperties dataShardProperties;

    @Override
    public boolean match(String propertyName, Object propertyValue, Object parameterObject, String columnName) {
        if (!(propertyValue instanceof String)) {
            return false;
        }
        if (MASK_PATTERN.matcher((String)propertyValue).matches()
            && !matchPropertyName(propertyName)) {
            //todo metric埋点
            String requestURI = Optional.ofNullable(RequestContext.getCurrentContext().getRequest()).map(r->r.getRequestURI()).orElse("Unknown");
            log.info(
                "Masked unrecognizable data wanna update to database, requestURI: {}, propertyName: {}, property: {}, parameterObject: {}",
                requestURI, propertyName, propertyValue, parameterObject);
        }
        return false;
    }

    private boolean matchPropertyName(String propertyName) {
        return DEFAULT_DESENSITIZATION_NAMES.contains(propertyName)
            || Optional.ofNullable(dataShardProperties.getCommonDesensitizationNames())
                .map(list -> list.contains(propertyName)).orElse(false);
    }
}
